package com.ado.abyss.core.web.controller;

import java.util.List;
import java.util.Set;

import com.ado.abyss.core.constants.LogEnum;
import com.ado.abyss.core.params.http.HttpResult;
import com.ado.abyss.core.params.page.PageRequest;
import com.ado.abyss.core.web.controller.base.BaseController;
import com.ado.abyss.core.web.utils.PasswordUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ado.abyss.core.constants.SysConstants;
import com.ado.abyss.core.dal.model.SysUser;
import com.ado.abyss.core.dal.model.SysUserRole;
import com.ado.abyss.core.service.SysUserService;


import lombok.extern.slf4j.Slf4j;

/***
 * 
 * @author adonais
 * @date 2020/05/20
 * @description 用户控制器
 *
 */
@Slf4j
@RestController
@RequestMapping(value = "/api/user")
public class UserController extends BaseController {

	//定义日志
	private static final Logger log = LoggerFactory.getLogger(UserController.class) ;

	@Autowired
	@Qualifier(value = "sysUserService")
	private SysUserService sysUserService;
	
	@PreAuthorize("hasAuthority('sys:user:add') AND hasAuthority('sys:user:edit')")
	@PostMapping(value="/save")
	public HttpResult save(@RequestBody SysUser record) {
		log.info("[{}]:[{}]" , "用户新增模块" , "新增入参"+record.toString());
		SysUser user = sysUserService.getById(record.getId());
		if(user != null) {
			if(SysConstants.ADMIN.equalsIgnoreCase(user.getName())) {
				return HttpResult.error("超级管理员不允许修改!");
			}
		}
		if(record.getPassword() != null) {
			String salt = PasswordUtils.getSalt();
			if(user == null) {
				// 新增用户
				if(sysUserService.findByName(record.getName()) != null) {
					return HttpResult.error("用户名已存在!");
				}
				String password = PasswordUtils.encode(record.getPassword(), salt);
				record.setSalt(salt);
				record.setPassword(password);
			} else {
				// 修改用户, 且修改了密码
				if(!record.getPassword().equals(user.getPassword())) {
					String password = PasswordUtils.encode(record.getPassword(), salt);
					record.setSalt(salt);
					record.setPassword(password);
				}
			}
		}
		boolean result = sysUserService.save(record);
		log.info("[{}]:[{}]" , "用户新增模块 -- End" , "新增结果" + result);
		return HttpResult.ok(result);
	}

	@PreAuthorize("hasAuthority('sys:user:delete')")
	@PostMapping(value="/delete")
	public HttpResult delete(@RequestBody List<SysUser> records) {
		log.info("[{}]:[{}]" , "用户删除模块 -- start");
		for(SysUser record:records) {
			SysUser sysUser = sysUserService.getById(record.getId());
			if(sysUser != null && SysConstants.ADMIN.equalsIgnoreCase(sysUser.getName())) {
				return HttpResult.error("超级管理员不允许删除!");
			}
		}
		boolean result = sysUserService.delete(records) ;
		log.info("[{}]:[{}]" , "用户删除模块 -- End" , "删除结果" + result);
		return HttpResult.ok(result);
	}
	
	@PreAuthorize("hasAuthority('sys:user:view')")
	@GetMapping(value="/findByName")
	public HttpResult findByUserName(@RequestParam String name) {
		log.info("[{}] : [{}]" , "用户查询模块" , "查询入参:" + name);
		SysUser sysUser = sysUserService.findByName(name) ;
		log.info("[{}] : [{}]" , "用户查询模块 -- End" , "查询结果" + sysUser.toString());
		return HttpResult.ok(sysUser);
	}
	
	@PreAuthorize("hasAuthority('sys:user:view')")
	@GetMapping(value="/findPermissions")
	public HttpResult findPermissions(@RequestParam String name) {
		log.info("[{}]:[{}]" , "用户查询模块" , "查询入参：" + name);
		Set<String> permissions = sysUserService.findPermissions(name) ;
		log.info("[{}]:[{}]" , "用户查询 -- End" , "查询出参" + permissions) ;
		return HttpResult.ok(permissions);
	}
	
	@PreAuthorize("hasAuthority('sys:user:view')")
	@GetMapping(value="/findUserRoles")
	public HttpResult findUserRoles(@RequestParam Long userId) {
		log.info("[{}]:[{}]" , "用户查询模块 -- start" , "查询入参:" + userId);
		List<SysUserRole> sysUserRoles = sysUserService.findUserRoles(userId) ;
		log.info("[{}]:[{}]" , "用户查询模块 -- End" , "查询结果:" + sysUserRoles.toString());
		return HttpResult.ok(sysUserRoles);
	}

	@PreAuthorize("hasAuthority('sys:user:view')")
	@PostMapping(value="/findPage")
	public HttpResult findPage(@RequestBody PageRequest pageRequest) {
		setLog(LogEnum.USER_MODULE.getModuleName() , "用户分页查询,查询入参:"+pageRequest.toString());
		setLog(LogEnum.USER_MODULE.getModuleName() , "用户分页查询,查询结果:"+sysUserService.findPage(pageRequest));
		return HttpResult.ok(sysUserService.findPage(pageRequest));
	}
	
	@PreAuthorize("hasAuthority('sys:user:view')")
	@GetMapping(value = "/findAll")
	public HttpResult findAll() {
		List<SysUser> sysUsers = sysUserService.findAll() ;
		setLog(LogEnum.USER_MODULE.getModuleName() , "查询结果为:" + sysUsers.toString());
		return HttpResult.ok(sysUsers) ;
 	}
}
